/**  
  -- The Performance Driven Lime Project -- 

  A self adaptive tuple space for mobile agents and hosts by dynamic
  adapting tuple's replication policy.
  
  Copyright (C) 2008
  Xing Jiankuan, Pan Wenhui
  SAGroup of Tsinghua University

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received this copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 */
package sagroup.dracots.testing;

import java.util.HashSet;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;

import lights.adapters.Field;
import lights.adapters.Tuple;
import lights.interfaces.ITuple;
import lime2.TupleID;

import sagroup.dracots.DracoTS;
import sagroup.dracots.DracoTuple;
import sagroup.dracots.FlatShareTuple;
import sagroup.dracots.TupleType;

public class OutgAgent implements Runnable {

	// This is the average value for exponential distribution of out frequency
	private long meaninterval;
	// This is the params for Gaussian distribution for size of tuple 
	private long mu, sigma;
	// Type of tuple
	private TupleType type;
	
	private boolean timesup = false;
	private int opCount = 0;
	private long begin;
	private long timing;

	private Logger LOG = Logger.getLogger(this.getClass().getName());

	// Make a new single tuple element
	static FlatShareTuple makeNewTuple(TupleType type, String aString){
		  ITuple it = new Tuple();
		  it.add(new Field().setValue("switch"));
		  it.add(new Field().setValue(aString));
		  return new FlatShareTuple(type,it);
	}
	
	/**
	 * 
	 */
	public OutgAgent(String typeName, String meaninterval, 
			String mu, String sigma) {

		this.type = new TupleType(typeName);

		this.meaninterval = Long.valueOf(meaninterval);
		this.mu = Long.valueOf(mu);
		this.sigma = Long.valueOf(sigma);

		if (this.meaninterval < 0 || this.mu < 0 || this.sigma < 0) {
			throw new IllegalArgumentException("Parameters are illegal.");
		}

		Timer timer = new Timer();
		TimerTask tt = new TimerTask() {
			@Override
			public void run() {
				timesup = true;
				timing = (System.nanoTime() - begin) / 1000 / 1000;
			}
		};
		timer.schedule(tt, AgentUtil.expTime);

	}	
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			DracoTS dts = DracoTS.get("testing");
			RandomData randomTimeGap = new RandomDataImpl();
			RandomData randomSize = new RandomDataImpl();
			
			System.out.println("type: " + type + " Mean interval: " + meaninterval);
			
			HashSet<TupleID> hashSet = new HashSet();
			while (!this.timesup) {
				double tupleSize = randomSize.nextGaussian(mu, sigma);
				char []pChar = new char[(int)tupleSize];
				if(pChar == null){
					System.out.println("Allocate failed!");
					System.exit(0);
				} else{
					pChar[0] = 'a';
					pChar[(int)tupleSize - 1] = 'z'; 
				}
				DracoTuple[] tuples = new DracoTuple[10];
				for(int i=0;i<10;i++)
				{
				String aString = new String(pChar);
				FlatShareTuple tempTuple = makeNewTuple(type, aString);
				hashSet.add(tempTuple.getVID());
				tuples[i] = tempTuple;
				}
				dts.outg(tuples);
				System.out.println(Thread.currentThread().getName()
						+ " has outed 10 new tuples");
				//System.out.println("Number: " + i + "\tLength: " + aString.length());
			

				opCount++;
				long sleeptime = (long) (randomTimeGap.nextExponential(1) * this.meaninterval);
				Thread.sleep(sleeptime);
			}
			dts.out(ListTuple.createLocalList(type, hashSet));				
			System.out.println(this.toString() + " Agent finishs all work.");
			
		}  catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			LOG.info("Out Agent: " + this.toString() + " " + this.getInfo());
		}
	}
	
	public String toString() {
		String id = "Agent Out " + ":" + Thread.currentThread().getName();
		String target = "Target type : " + type + " ; Mean interval: "
				+ this.meaninterval + " .";
		return id + ", " + target;
	}

	private String getInfo() {
		String info = "Operation times : " + this.opCount + " Timing : "
				+ this.timing + ". Average : "
				+ ((this.opCount != 0) ? this.timing / this.opCount : null);
		return info;
	}
}

